package com.loiot.baqi.service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.loiot.baqi.commons.message.email.EmailClient;
import com.loiot.baqi.commons.message.email.SimpleEmailVo;
import com.loiot.baqi.constant.ApplicationConst;
import com.loiot.baqi.constant.DictionaryUtil;
import com.loiot.baqi.controller.response.Pager;
import com.loiot.baqi.dao.AccountDao;
import com.loiot.baqi.dao.AccountExpandInfoDao;
import com.loiot.baqi.dao.BaseDao;
import com.loiot.baqi.dao.FileDao;
import com.loiot.baqi.dao.TgQqGroupDao;
import com.loiot.baqi.dao.TgQqGroupLeaderDao;
import com.loiot.baqi.dao.WeiAccountQqGroupBusinessDao;
import com.loiot.baqi.dao.WeiAccountQqGroupLeaderDao;
import com.loiot.baqi.page.PageParameter;
import com.loiot.baqi.pojo.AccountExpandInfo;
import com.loiot.baqi.pojo.File;
import com.loiot.baqi.pojo.TgQqGroup;
import com.loiot.baqi.pojo.TgQqGroupLeader;
import com.loiot.baqi.pojo.WeiAccountQqGroupBusiness;
import com.loiot.baqi.pojo.WeiAccountQqGroupLeader;
import com.loiot.baqi.status.AccountType;
import com.loiot.baqi.status.DictionaryType;
import com.loiot.baqi.status.JlAuditCountType;
import com.loiot.baqi.status.PauseStartType;
import com.loiot.baqi.utils.MD5Util;
import com.loiot.baqi.utils.RandomUtil;
import com.loiot.baqi.utils.UserSessionUtils;
import com.loiot.commons.utils.DateUtil;
import com.loiot.commons.utils.StringUtil;
import com.timeloit.pojo.Account;
import com.timeloit.pojo.Role;


/**
 * 商务谈判 逻辑类。
 * 
 * @author  xuyb 
 * @creation 2016-08-28
 */
@Service("weiAccountQqGroupBusinessService")
@Transactional
public class WeiAccountQqGroupBusinessService{
    
    private Logger log = LoggerFactory.getLogger(this.getClass());
    
    @Resource
	private WeiAccountQqGroupBusinessDao weiAccountQqGroupBusinessDao;
    
    @Autowired
    private FileDao fileDao;//图片服务
    @Autowired
    private  BaseDao baseDao;//basedao
    @Autowired
    private AccountDao accountDao;//用户dao
    @Autowired
    private AccountExpandInfoDao accountExpandInfoDao;//用户附加信息Dao
    @Autowired
    private TgQqGroupDao tgQqGroupDao;//群dao
    @Autowired
    private EmailClient emailClient;//邮件dao
    @Autowired
    private TgQqGroupLeaderDao tgQqGroupLeaderDao;//QQ群主dao
    
    @Autowired
    private WeiAccountQqGroupLeaderDao weiAccountQqGroupLeaderDao;//QQ群主dao
	
	 /**
     * 查询 商务谈判列表分页
     * 
     * @param name 商务谈判名称d
     * @param pageIndex 页索引
     * @return
     */
    public Pager<WeiAccountQqGroupBusiness> queryWeiAccountQqGroupBusinessListPage(HashMap<String,Object> pMap, int pageIndex)throws Exception {

        // 查询商务谈判列表总条数
        int totalResults = weiAccountQqGroupBusinessDao.getWeiAccountQqGroupBusinessListCount(pMap);

        // 构造一个分页器
        Pager<WeiAccountQqGroupBusiness> pager = new Pager<WeiAccountQqGroupBusiness>(totalResults, pageIndex);

        // 查询商务谈判列表
        List<WeiAccountQqGroupBusiness> weiAccountQqGroupBusinessList = weiAccountQqGroupBusinessDao.queryWeiAccountQqGroupBusinessList(pMap, pager.getSkipResults(),
                pager.getMaxResults());
        pager.setData(weiAccountQqGroupBusinessList);
        return pager;
    }
    
   /* public PageParameter queryWeiAccountQqGroupBusinessListPage(HashMap<String,Object> pMap, int pageIndex)throws Exception {
    	//创建分页参数Map
		PageParameter pageParameter = getPageMap(pMap, pageIndex, 10);
		//查询数据
		List<WeiAccountQqGroupBusiness> userInfoList = weiAccountQqGroupBusinessDao.queryWeiAccountQqGroupBusinessList(pMap);
		//设置分页后的数据
		pageParameter.setDatas(userInfoList);
		return pageParameter;
    }*/
    
    
    
    /**
	 * TODO: 获取分页Map
	 * @Auhor: RICK
	 * @Date : 2016年9月27日
	 */
	protected PageParameter getPageMap(Map<String, Object> map, int currentPage, int pageSize) {
		PageParameter page = new PageParameter(currentPage, pageSize);
		map.put("page", page);
		return page;
	}
    
    
    /**
     * 查询 商务谈判（假）分页
     * 
     * @param name 商务谈判名称
     * @param pageIndex 页索引
     * @return
     */
    public Pager<WeiAccountQqGroupBusiness> queryFlasePageList(HashMap<String,Object> pMap, int pageIndex)throws Exception {
    	//假分页
    	Pager<WeiAccountQqGroupBusiness> pager = this.setPkList(pMap,pageIndex);
    	List<WeiAccountQqGroupBusiness> weiAccountQqGroupBusinessList = weiAccountQqGroupBusinessDao.queryWeiAccountQqGroupBusinessList(pMap);
        pager.setData(weiAccountQqGroupBusinessList);
        return pager;
    }
    
    /**
     * 设置 假分页id集合到Map中
     * @param pMap
     * @param pageIndex
     * @return
     * @throws Exception
     */
    public Pager<WeiAccountQqGroupBusiness> setPkList(HashMap<String,Object> pMap,int pageIndex) throws Exception{
    	  // 查询职位匹配信息列表总条数
        List<WeiAccountQqGroupBusiness> list = weiAccountQqGroupBusinessDao.queryWeiAccountQqGroupBusinessList(pMap);
        // 构造一个分页器
        Pager<WeiAccountQqGroupBusiness> pager = new Pager<WeiAccountQqGroupBusiness>(list.size(), pageIndex, 5,list);
        List<WeiAccountQqGroupBusiness> idsList = pager.getCurrentPageData();
        List<Long> ids =this.getIds(idsList);
        pMap.put("ids", ids);
        return pager;
    }
	
	 /**
     * 添加 商务谈判
     * 
     * @param p 参数对象
     */
    public WeiAccountQqGroupBusiness addWeiAccountQqGroupBusiness(WeiAccountQqGroupBusiness p)throws Exception {
       return  weiAccountQqGroupBusinessDao.addWeiAccountQqGroupBusiness(p);
    }
    
    /**
     * 修改 商务谈判
     * 
     * @param p 参数对象
     */
    public void updateWeiAccountQqGroupBusiness(WeiAccountQqGroupBusiness p)throws Exception {
        weiAccountQqGroupBusinessDao.updateWeiAccountQqGroupBusiness(p);
    }
    
    /**
     * 修改 商务谈判
     * 
     * @param p 参数对象
     */
    public void updateWeiAccountQqGroupBusiness(HashMap<String,Object> pMap)throws Exception {
        weiAccountQqGroupBusinessDao.updateWeiAccountQqGroupBusiness(pMap);
    }
    
    /**
     * 删除  商务谈判
     * 
     * @param id 主键
     */
    public void deleteWeiAccountQqGroupBusiness(java.lang.Long id)throws Exception {
        weiAccountQqGroupBusinessDao.deleteWeiAccountQqGroupBusiness(id);
    }
    
    /**
     * 删除  商务谈判
     * 
     * @param id 主键
     */
    public void deleteWeiAccountQqGroupBusiness(WeiAccountQqGroupBusiness p)throws Exception {
        weiAccountQqGroupBusinessDao.deleteWeiAccountQqGroupBusiness(p);
    }
    
    /**
     * 获得  商务谈判
     * 
     * @param id 商务谈判Id
     * 
     * @return 返回与ID匹配的商务谈判
     */
    public WeiAccountQqGroupBusiness getWeiAccountQqGroupBusinessById(java.lang.Long id)throws Exception {
        return  weiAccountQqGroupBusinessDao.getWeiAccountQqGroupBusinessById(id);
    }
    
    /**
     * 获得  商务谈判
     * 
     * @param id 商务谈判Id
     * 
     * @return 返回与ID匹配的商务谈判
     */
    public WeiAccountQqGroupBusiness getWeiAccountQqGroupBusinessById(java.lang.Long id,Long accountId)throws Exception {
        return  weiAccountQqGroupBusinessDao.getWeiAccountQqGroupBusinessById(id,accountId);
    }
    
    
    /**
     * 获得  商务谈判
     * 
     * @param id 商务谈判Id
     * 
     */
    public WeiAccountQqGroupBusiness getWeiAccountQqGroupBusiness(HashMap<String,Object> pMap)throws Exception {
    	return (WeiAccountQqGroupBusiness) weiAccountQqGroupBusinessDao.getWeiAccountQqGroupBusiness(pMap);
    }
    /**
     * 获得  商务谈判
     * 
     * @param name 商务谈判名称
     * 
     * @return 返回与NAME匹配的商务谈判
     */
    public WeiAccountQqGroupBusiness getWeiAccountQqGroupBusinessByName(String name)throws Exception {
        return  weiAccountQqGroupBusinessDao.getWeiAccountQqGroupBusinessByName(name);
    }
    
    /**
     * 查询 商务谈判列表
     * @return 商务谈判列表
     */
    public List<WeiAccountQqGroupBusiness> queryWeiAccountQqGroupBusinessList(HashMap<String,Object> pMap)throws Exception {
        return  weiAccountQqGroupBusinessDao.queryWeiAccountQqGroupBusinessList(pMap);
    }
    
    /**
     * 查询 商务谈判列表
     * @return 商务谈判列表
     */
    public List<WeiAccountQqGroupBusiness> queryWeiAccountQqGroupBusinessList(WeiAccountQqGroupBusiness p)throws Exception {
        return  weiAccountQqGroupBusinessDao.queryWeiAccountQqGroupBusinessList(p);
    }
    
    /**
     * 查询  商务谈判列表条数
     * 
     * @param name 商务谈判名称
     * @return 商务谈判列表条数
     */
    
    public int getWeiAccountQqGroupBusinessListCount(HashMap<String,Object> pMap)throws Exception {
        return  weiAccountQqGroupBusinessDao.getWeiAccountQqGroupBusinessListCount(pMap);
    }
    
    /**
     * 查询id集合
     * @return
     */
    public List<Long> getIds(List<WeiAccountQqGroupBusiness> list) {
    	List<Long> idsList = null;
        if(list!=null && list.size()>0) {
        	idsList = new ArrayList<Long>();
        	for (WeiAccountQqGroupBusiness b : list) {
            	idsList.add(null);
            }
        }
        return idsList;
    }
    
    /**
     * 统计 商务谈判列表
     * 
     * @return 商务谈判列表
     */
    public List<HashMap<String,Object>> statisticsWeiAccountQqGroupBusinessInfo(HashMap<String, Object> pMap )throws Exception {
    	return  weiAccountQqGroupBusinessDao.statisticsWeiAccountQqGroupBusinessInfo(pMap);
    }
    
    /**
     * TODO: 保存同意
     * @Auhor: RICK
     * @Date : 2016年9月9日
     */
    public int saveAgree(HashMap<String,Object> pMap,Account account3)throws Exception {
    	int result = 0;
    	result = weiAccountQqGroupBusinessDao.saveAgree(pMap);
    	//保存上传的图片
    	File file = null;
    	List<File> fileList = new ArrayList<File>();
    	if (result == 1) {
    		String[] imgs = pMap.get("productImg").toString().split(",");
    		long dataId = Long.parseLong(pMap.get("id").toString());
    		long createId = Long.parseLong(pMap.get("inPerson").toString());
    		for (String imgUrl : imgs) {
    			file = new File();
        		file.setDataId(dataId);
        		file.setFilePath(imgUrl);
        		file.setStatus("1");
        		file.setBusiness("1");
        		file.setCreateId(createId);
        		file.setCreateDate(Calendar.getInstance().getTime());
        		fileList.add(file);
			}
    		//批量新增
    		fileDao.addWeiAccountQqGroupBatch(fileList);
    		
    		
    		//查询微商户
        	WeiAccountQqGroupBusiness wei = weiAccountQqGroupBusinessDao.getWeiAccountQqGroupBusinessById(Long.parseLong(pMap.get("id").toString()));
        	//查询群主信息
        	Map<String, Object> selMap = new HashMap<String, Object>();
        	selMap.put("id", wei.getGroupId());
        	TgQqGroup tgQqGroup = tgQqGroupDao.getTgQqGroup((HashMap<String, Object>) selMap);
        	
        	Account accoun=accountDao.getAccountByUsername(String.valueOf(tgQqGroup.getLeaderNumber()));
        	
        	if(accoun==null){
        		//tgQqGroup.getLeaderNumber()
        		//生成群主用户信息
        		final String userName = String.valueOf(tgQqGroup.getLeaderNumber());//群主QQ号
        		final String passWord = RandomUtil.getRandomStr(6);//生成随机6位密码
        		account3.setUsername(userName);//账号名
        		account3.setPassword(MD5Util.encodePassword(passWord));//密码
        		
        		account3.setType((int) AccountType.QQ_GROUP_LEADER.getCode());//账号类型
        		
        		//创建群主角色ID
        		Role role = new Role();
        		role.setRoleId(Long.parseLong(ApplicationConst.QQ_GROUPLADER_ROLE_ID));
        		account3.setRole(role);
        		accountDao.addAccount(account3);
        		//添加角色
        		accountDao.addAccountRole(account3.getAccountId(), account3.getRole().getRoleId());
        		
        		//扩展信息
        		AccountExpandInfo expandInfo = new AccountExpandInfo();
        		expandInfo.setAccountId(account3.getAccountId());
        		expandInfo.setInPerson(account3.getAccountId());
        		expandInfo.setInTime(account3.getInTime());
        		expandInfo.setAuditPositionId(account3.getAuditPositionId());
        		expandInfo.setQq(account3.getQq());
        		accountExpandInfoDao.addAccountExpandInfo(expandInfo);
        	 	//发送邮件推送给群主
            	new Thread(){ 
        	      	  @Override 
        	      	  public void run() { 
        	      	       String email = userName +"@qq.com";
        	      	        if(email!=null && StringUtil.isEmail(email) ){
        	      	         SimpleEmailVo vo = new SimpleEmailVo();
        	      	            vo.addEmail(email);
        	      	                     vo.setTitle("群主账号生成");
        	      	                     vo.setContent(ApplicationConst.getMessage("10109", userName,passWord));
        	      	                     emailClient.send(vo);
        	      	                     log.info("发送时间："+DateUtil.toString(DateUtil.getNow(), DateUtil.DEFAULT_LONG_FORMAT));
        	      	        }
        	      	  } 
                  }.start();
                  accoun = new Account();
                  accoun.setAccountId(account3.getAccountId());
        	}
            
            //新增一条QQ群主信息  tg_qq_group_leader
            WeiAccountQqGroupLeader weiQqGroupLeader = new WeiAccountQqGroupLeader();
            weiQqGroupLeader.setGroup(tgQqGroup);
            weiQqGroupLeader.setAccountId(accoun.getAccountId());
            weiQqGroupLeader.setGroupId(tgQqGroup.getId());
            weiQqGroupLeader.setInTime(Calendar.getInstance().getTime());
            weiQqGroupLeader.setInPerson(UserSessionUtils.getAccount().getAccountId());
            //weiAccountQqGroupLeaderDao.addWeiAccountQqGroupLeader(weiQqGroupLeader);
            baseDao.addV1(weiQqGroupLeader);
            //告错瑞波了,应该往上面这个类里加
            /*TgQqGroupLeader qqGroupLeader = new TgQqGroupLeader();
            qqGroupLeader.setGroupId(Long.parseLong(tgQqGroup.getId()+""));//所属qq群
            qqGroupLeader.setNumber(StringUtil.isNotBlank(tgQqGroup.getLeaderNumber())?tgQqGroup.getLeaderNumber():"");//qq号
            qqGroupLeader.setName(StringUtil.isNotBlank(tgQqGroup.getLeaderNickname())?tgQqGroup.getLeaderNickname():"");//昵称
            qqGroupLeader.setType("1");//1 群主 2 管理员
            qqGroupLeader.setInTime(Calendar.getInstance().getTime());//录入时间
            qqGroupLeader.setInPerson(String.valueOf(account.getAccountId()));//录入人
            tgQqGroupLeaderDao.addTgQqGroupLeader(qqGroupLeader);*/
        	
        	
       
		}
    	
    	return result;
    }
    
    /**
     * TODO: 保存拒绝合作原因
     * @Auhor: RICK
     * @Date : 2016年9月9日
     */
    public int saveRefuse(HashMap<String,Object> pMap)throws Exception {
    	return weiAccountQqGroupBusinessDao.saveRefuse(pMap);
    }
    /**
     * 根据id更新对象
     */
    public void updateWeiAccountQqGroupBusinessByID(WeiAccountQqGroupBusiness w){
    	try {
			baseDao.updateByPkV1(w);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}
